package com.sk.rpcAssist.consumerAssist;

import com.sk.rpcAssist.annotation.loadBalancer.LoadBalancerRule;
import com.sk.rpcAssist.dataManager.ConsumerDataManager;
import com.sk.rpcAssist.dataManager.DefaultConsumerDataManager;
import com.sk.rpcAssist.io.protocol.RpcRequest;
import com.sk.rpcAssist.policy.ServiceBeanDefinitionRegistry;
import com.sk.rpcAssist.util.ObjectUtil;

import java.util.Map;

/**
 * description：rpc消费者端策略容器
 *
 * @author 孙文斌
 * @Date: 2021/2/4 17:40
 */
public class ConsumerAssistStrategyContent {

    //策略接口
    private ConsumerAssistStrategyInter consumerAssistStrategy;

    public static ConsumerAssistStrategyContent getInstance() {
        ConsumerAssistStrategyInter current = null;
        //判断当前ConsumerAssistStrategyInter有无用户自定义实现类
        Map<String, ConsumerAssistStrategyInter> beanMap = ServiceBeanDefinitionRegistry.applicationContext.getBeansOfType(ConsumerAssistStrategyInter.class);
        //用户提供了策略
        if(beanMap.isEmpty()){
            current = new DefaultConsumerAstStrategy();
        }else if (!beanMap.isEmpty() && beanMap.size() > 1) {
            throw new RuntimeException("Expected only one implementation class for ConsumerAssistStrategyInter interface, but found multiple,interfaces info :" + ConsumerAssistStrategyInter.class.getName());
        }else {
            current = (ConsumerAssistStrategyInter) beanMap.values().toArray()[0];
        }
        return new ConsumerAssistStrategyContent(current);
    }

    private ConsumerAssistStrategyContent(ConsumerAssistStrategyInter consumerAssistStrategyInter) {
        this.consumerAssistStrategy = consumerAssistStrategyInter;
    }

    public final Object invoke(RpcRequest rpcRequest) {
        ObjectUtil.checkNotNull(this.consumerAssistStrategy, "consumer assist Strategy is null");
        return consumerAssistStrategy.invoke(rpcRequest);
    }
}
